﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace RQX.Common.Core.Authority
{
    /// <summary>
    /// 加密类
    /// </summary>
    public class CypherUtils
    {
        private const string Key = "RQX.Common.Core.2020.!@#$*&^%";

        /// <summary>
        /// DES加密
        /// </summary>
        /// <param name="originalMsg"></param>
        /// <returns></returns>
        public static string DESEncrypt(string originalMsg)
        {
            return DESEncrypt(originalMsg, Key);
        }
        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="cypherMsg"></param>
        /// <returns></returns>
        public static string DESDecrypt(string cypherMsg)
        {
            return DESDecrypt(cypherMsg, Key);
        }


        private static byte[] GetKey(string key)
        {
            using var md5 = MD5.Create();
            return Encoding.UTF8.GetBytes(Convert.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(key))).Substring(0, 8));
        }

        /// <summary>
        /// 加密数据
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        private static string DESEncrypt(string msg, string key)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            using MemoryStream ms = new MemoryStream();

            var msgBytes = Encoding.UTF8.GetBytes(msg);
            var keyBytes = GetKey(key);

            using CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(keyBytes, keyBytes), CryptoStreamMode.Write);
            cs.Write(msgBytes, 0, msgBytes.Length);
            cs.FlushFinalBlock();
            return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
        }

        /// <summary> 
		/// 解密数据 
		/// </summary> 
		/// <param name="cypherMsg"></param> 
		/// <param name="key"></param> 
		/// <returns></returns> 
		private static string DESDecrypt(string cypherMsg, string key)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            using MemoryStream ms = new MemoryStream();

            var msgBytes = Convert.FromBase64String(cypherMsg);
            var keyBytes = GetKey(key);

            using CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(keyBytes, keyBytes), CryptoStreamMode.Write);
            cs.Write(msgBytes, 0, msgBytes.Length);
            cs.FlushFinalBlock();
            return Encoding.UTF8.GetString(ms.ToArray());
        }
    }
}
